/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 */

import path from 'path';

import { expect } from '@jest/globals';
import fse from 'fs-extra';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption, TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

/**
 * 测试工程选项
 *
 * @type {{template: ProjectTemplateOption}}
 */
const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
};

const testTaskOption: TestTaskOption = TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L2).sign(SignType.NoSign).ohpmInstall(IsEnable.Enable).build();

/**
 * 测试函数
 *
 * @param {Project} project 测试工程对象
 * @param {TestTaskOption} taskConfig 测试操作可选项
 * @param {ICaseRecord} record 测试记录
 * @return {Promise<void>}
 */
const testFun: TestCaseFun = async (project, taskConfig, record) => {
  // 测试工程主目录路径
  const projectRootPath = project.projectRootPath();

  // 需要执行的命令行参数
  const commands = initExecuteCommand({
    product: 'default1',
    tasks: 'sync',
    daemon: true,
    sync: true,
  });

  // 修改entry的buildProfile
  fse.writeFileSync(
    path.resolve(projectRootPath, 'build-profile.json5'),
    `
{
  "app": {
    "signingConfigs": [],
    "products": [
      {
        "name": "default",
        "signingConfig": "default",
        "compatibleSdkVersion": "5.1.0(18)",
        "runtimeOS": "HarmonyOS",
        "buildOption": {
          "strictMode": {
            "caseSensitiveCheck": true,
            "useNormalizedOHMUrl": true
          }
        }
      },
      {
        "name": "default1",
        "signingConfig": "default",
        "compatibleSdkVersion": "5.1.0(18)",
        "runtimeOS": "HarmonyOS",
        "buildOption": {
          "strictMode": {
            "caseSensitiveCheck": true,
            "useNormalizedOHMUrl": true
          }
        }
      }
    ],
    "buildModeSet": [
      {
        "name": "debug",
      },
      {
        "name": "release"
      }
    ]
  },
  "modules": [
    {
      "name": "entry",
      "srcPath": "./entry",
      "targets": [
        {
          "name": "default",
          "applyToProducts": [
            "default"
          ]
        },
        {
          "name": "default1",
          "applyToProducts": [
            "default1"
          ]
        }
      ]
    }
  ]
}
  `,
  );

  fse.writeFileSync(
    path.resolve(projectRootPath, 'entry', 'build-profile.json5'),
    `
{
  "apiType": "stageMode",
  "buildOption": {
  },
  "buildOptionSet": [
    {
      "name": "release",
      "arkOptions": {
        "obfuscation": {
          "ruleOptions": {
            "enable": false,
            "files": [
              "./obfuscation-rules.txt"
            ]
          }
        }
      }
    },
  ],
  "targets": [
    {
      "name": "default"
    }, {
      "name": "default1"
    },
    {
      "name": "ohosTest",
    }
  ]
}
  `,
  );

  // 执行编译
  const result = await runHvigorAsync(projectRootPath, commands);

  // 记录测试日志
  record.addStep('Build App', result);

  // 使用断言判断执行结果
  expect(result.stdout).toContain('Finished :entry:init...');
  expect(result.stdout).toContain('Finished ::init... after 1 ms');
};

// 将demo测试用例注册到测试用例中心
TestCaseBuilder.builder()
  .caseName('DTS2024122516907')
  .description('Sync的时候不会报错')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(testTaskOption)
  .testFun(testFun)
  .load();
